package service

import (
	"file_sys_server/model"
	"file_sys_server/serializer"
	"file_sys_server/utils"

	"gorm.io/gorm"
)

type ProjectService struct {
}

// 读取本地Excel数据存储到mysql数据库
func AddProejctsFromLocal() serializer.Response {
	records, err := utils.ConvertProjectToBean() // 直接读本地值
	if err != nil {
		return serializer.Response{
			Code: 10003,
			Msg:  err.Error(),
		}
	}

	// err = model.DB.CreateInBatches(records, len(records)).Error
	err = insertOrReplace(model.DB, records) // 批量插入

	if err != nil {
		return serializer.Response{
			Code: 10003,
			Msg:  err.Error(),
		}
	}

	return serializer.Response{
		Code: 10000,
		Msg:  "success",
	}
}

func insertOrReplace(db *gorm.DB, projs []*model.Project_bean_mfdcg) error {
	for _, pro := range projs {
		var oldProj model.Project_bean_mfdcg

		// fmt.Println("qrstr: " + pro.QrcodeStr)
		err := db.Where("qrcodeStr=?", pro.QrcodeStr).FirstOrCreate(&oldProj).Error
		if err != nil {
			return err
		}
		// id := fmt.Sprintf("%d", oldProj.ID)
		// fmt.Println("insertOrReplace :" + oldProj.QrcodeStr)
		// fmt.Println("insertOrReplace :" + oldProj.ProjectName)
		// fmt.Println("insertOrReplace :" + id)
		if oldProj.ID == 0 {
			if err := db.Create(pro).Error; err != nil {
				return err
			}
		} else {
			pro.ID = oldProj.ID

			if err := db.Save(pro).Error; err != nil {
				return err
			}
		}
	}
	return nil
}

// 获取样品列表数据
func GetProjectList() serializer.Response {
	var projects []*model.Project_bean_mfdcg
	err := model.DB.Find(&projects).Error

	if err != nil {
		return serializer.Response{
			Code: 10003,
			Msg:  err.Error(),
		}
	}

	return serializer.Response{
		Code: 10000,
		Msg:  "success",
		Data: serializer.BuildProejcts(projects),
	}
}
